// miniprogram/pages/NX_newMission/newMission.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: 0,
    projectId: '',
    create: false,

    missionId: null,
    missionName: null,
    missionTarget: null,

    startMode: 0,
    missionStart: null,
    missionRequest: false,
    missionEnd: null,
    missionLast: null,

    allCheck: false,
    startPoint: null,
    master: false,
    group: null,
    mission: [],
    missionList: [],
    missionSelect: [0, 0],
    member: [],
    onlyRead: [false, false, false, false],
    styleList: [
      '',
      'top:calc(100% - 140px);transform:scale(1.1)',
      'top:calc(100% - 90px);transform:scale(1.3)',
      'top:calc(100% - 30px);transform:scale(1.5)'
    ],

    targetValue: null,
    targetArray: [],

    createConfirm: false,
    confirmed: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    options.create = options.create == 'true';
    options.master = options.master == 'true';
    if (!options.create) {
      wx.setNavigationBarTitle({
        title: '修改任务',
      })
    }
    if (!options.create) {
      this.setTile();
      if (options.missionId) {
        const detail = getApp().globalData.tempMissionDetail;
        let startMode = 0,
          missionStart = null,
          missionEnd = null,
          missionLast = null;
        new Promise((resolve) => {
          if (detail.front && detail.front.length) {
            startMode = 1;
            missionLast = detail.last;
            wx.cloud.callFunction({
              name: 'getMissionInfo',
              data: {
                id: detail.front[0]
              }
            }).then(res => {
              missionStart = res.result;
              resolve();
            })
          } else {
            missionStart = detail.start;
            missionEnd = detail.end;
            resolve();
          }
        }).then(() => {
          this.setData({
            missionName: detail.name,
            startMode,
            missionStart,
            missionEnd,
            missionLast
          })
        })
      }
    }
    const targetArray = [{
      id: '0',
      name: '我'
    }]
    const tempProject = getApp().globalData.tempProject;
    const selfId = getApp().globalData.userInfo._id;
    new Promise(resolve => {
      if (tempProject && tempProject.group._id === options.projectId) {
        this.data.group = tempProject.group;
        this.data.mission = tempProject.mission.filter(user => user._id !== selfId);
        this.data.member = tempProject.member;
        resolve()
      } else {
        //如果没有项目临时存储则从服务器拉取数据
        wx.cloud.callFunction({
          name: 'getGroupInfo',
          data: {
            group: options.projectId,
            needDetail: true
          }
        }).then(res => {
          this.data.group = res.result.group;
          this.data.member = res.result.member;
          //按用户分开任务
          const userMap = new Map();
          const mission = [];
          for (const mission of res.result.mission) {
            if (mission.userId !== selfId) {
              if (userMap.has(mission.userId)) {
                userMap.get(mission.userId).mission.push(mission)
              } else {
                userMap.set(mission.userId, {
                  mission: [mission],
                  _id: mission.userId,
                  name: mission.userName
                });
              }
            }
          }
          for (const [, value] of userMap) {
            mission.push(value);
          }
          this.data.mission = mission;
          resolve();
        })
      }
    }).then(() => {
      if (options.master) {
        for (const member of this.data.member) {
          if (member._id !== selfId) {
            targetArray.push({
              id: member._id,
              name: member.userName
            })
          }
        }
      }
      if (!options.master) {
        this.setData({
          targetValue: 0
        })
        this.data.missionTarget= '0';

      }
      //整理任务节点列表
      const missionList = [];
      if (this.data.mission.length) {
        missionList[0] = this.data.mission;
        missionList[1] = this.data.mission[0].mission;
        missionList[1].push({
          _id: 'create',
          name: '创建任务委托'
        })
      } else {
        missionList[0] = [];
      }
      const missionUserList = missionList[0].map(usr => usr._id)
      for (const member of this.data.member) {
        if (member._id !== selfId && !missionUserList.includes(member._id)) {
          missionList[0].push({
            _id: member._id,
            name: member.userName,
            mission: [{
              _id: 'create',
              name: '创建任务委托'
            }]
          })
        }
      }
      if (missionList[0].length && !missionList[1]) {
        missionList[1] = missionList[0][0].mission;
      }
      this.setData({
        ...options,
        missionList,
        targetArray,
        group: this.data.group,
        mission: this.data.mission,
        member: this.data.member
      })
    })


  },
  setTile() {
    this.setData({
      styleList: this.styleLib.allTile,
      index: -1
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },
  changeStartMode() {
    this.setData({
      startMode: (this.data.startMode + 1) % 2,
      missionStart: null,
      missionEnd: null,
      missionRequest: false,
      missionLast: null,
    })
  },
  changeMissionStartPointCol(e) {
    this.data.missionSelect[e.detail.column] = e.detail.value;
    if (e.detail.column === 0) {
      this.data.missionList[1] = this.data.missionList[0][e.detail.value].mission
      if (this.data.missionList[1][this.data.missionList[1].length - 1]._id !== 'create') {
        this.data.missionList[1].push({
          _id: 'create',
          name: '创建任务委托'
        })
      }
    }
    this.setData({
      missionSelect: this.data.missionSelect,
      missionList: this.data.missionList
    })
  },
  changeMissionStartPoint(e) {
    const user = this.data.missionList[0][e.detail.value[0]];
    const mission = this.data.missionList[1][e.detail.value[1]];
    let missionRequest = false;
    let checkFlag = false;
    this.data.missionStart = false;
    if (mission._id === 'create') {
      //进行任务创建准备
      // console.log('任务创建')
      missionRequest = {
        _id: user._id,
        name: user.name,
        description: null
      };
    } else {
      this.data.missionStart = {
        ...mission
      }
      checkFlag = true;
    }
    this.setData({
      missionSelect: e.detail.value,
      missionStart: this.data.missionStart,
      missionRequest
    })
    if (checkFlag) this.doConfirm();
  },
  inputRequest(e) {
    this.data.missionRequest.description = e.detail.value;
    this.setData({
      missionRequest: this.data.missionRequest
    })
  },
  inputRange(e) {
    this.setData({
      missionLast: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  input(e) {
    // console.log(e)
    this.setData({
      missionName: e.detail.value
    })
  },
  styleLib: {
    nameFocus: [
      '',
      'top:calc(100% - 140px);transform:scale(1.1)',
      'top:calc(100% - 90px);transform:scale(1.3)',
      'top:calc(100% - 30px);transform:scale(1.5)'
    ],
    targetFocus: [
      'top:-5px;transform:scale(0.9)',
      'top:45px;',
      'top:calc(100% - 140px);transform:scale(1.1)',
      'top:calc(100% - 30px);transform:scale(1.3)'
    ],
    startFocus: [
      'top:-10px;transform:scale(0.8)',
      'top:25px;transform:scale(0.9)',
      'top:60px',
      'top:calc(100% - 30px);transform:scale(1.1)'
    ],
    endFocus: [
      'top:-12px;transform:scale(0.7)',
      'top:20px;transform:scale(0.8)',
      'top:50px;transform:scale(0.9)',
      'top:95px'
    ],
    allTile: [
      'position:absolute;top:10px',
      'position:absolute;top:122px',
      'position:absolute;top:230px',
      'position:absolute;top:340px'
    ],
    allTile2: [
      'position:relative;left:12.5px;transition:none;',
      'position:relative;left:12.5px;transition:none;',
      'position:relative;left:12.5px;transition:none;',
      'position:relative;left:12.5px;transition:none;'
    ]
  },

  doConfirm() {
    let allCheck = false;
    if (!this.data.missionName) {
      this.selectName();
    } else if (!this.data.missionTarget) {
      this.selectTarget();
    } else {
      if (this.data.startMode === 0) {
        if (!this.data.missionStart) {
          this.selectStart();
        } else if (!this.data.missionEnd) {
          this.selectEnd();
        } else {
          this.setData({
            index: -1,
            styleList: this.styleLib.allTile,
          })
          allCheck = true;
          //提交
        }
      } else if (this.data.startMode === 1) {
        if (!this.data.missionStart && !this.data.missionRequest) {
          this.selectStart();
        } else if (this.data.missionRequest && (!this.data.missionRequest.description || !this.data.missionRequest.description.length)) {
          this.selectStart();
        } else if (!this.data.missionLast) {
          this.selectEnd();
        } else {
          this.setData({
            index: -1,
            styleList: this.styleLib.allTile,
          })
          allCheck = true;
        }
      }
    }
    this.setData({
      allCheck
    })
    return allCheck;
  },
  selectName() {
    // if (this.data.create) {
    this.setData({
      index: 0,
      styleList: this.styleLib.nameFocus
    })
    wx.pageScrollTo({
      scrollTop: 0
    })
    // }
  },

  selectTarget() {
    // if (this.data.create) {
    this.setData({
      index: 1,
      styleList: this.styleLib.targetFocus
    })

    // }
  },
  changeTarget(e) {
    this.setData({
      targetValue: e.detail.value,
    })
    this.data.missionTarget = this.data.targetArray[e.detail.value].id

    this.doConfirm();
  },
  selectStart() {
    // if (this.data.create) {
    this.setData({
      index: 2,
      styleList: this.styleLib.startFocus
    })
    // }
  },
  changeStart(e) {
    this.setData({
      missionStart: `${e.detail.year}-${e.detail.month}-${e.detail.date}`
    })
    setTimeout(() => {
      this.doConfirm();
    }, 500)
  },
  changeEnd(e) {
    this.setData({
      missionEnd: `${e.detail.year}-${e.detail.month}-${e.detail.date}`
    })
    setTimeout(() => {
      this.doConfirm();
    }, 500)
  },
  selectEnd() {
    // if (this.data.create) {
    this.setData({
      index: 3,
      styleList: this.styleLib.endFocus
    })
    // }
  },

  tryCreate() {
    if (!this.doConfirm()) return
    if (!this.data.confirmed) {
      wx.showModal({
        title: '提示',
        content: this.data.create ? '确认创建任务吗' : '确认修改任务吗',
        success: res => {
          if (res.confirm) {
            // console.log('用户点击确定')
            this.doCreate()
          } else if (res.cancel) {}
        }
      })
    }
  },
  doCreate() {
    this.setData({
      createConfirm: null,
      confirmed: true
    })
    const projectId = this.data.projectId;
    const status = 'create';
    const init = true;
    let userId, userName, start, end, front = [],
      back = [],
      last, name = this.data.missionName
    if (this.data.missionTarget == '0') {
      userId = getApp().globalData.userInfo._id;
      userName = getApp().globalData.userInfo.userName;
    } else {
      userId = this.data.targetArray[this.data.targetValue].id;
      userName = this.data.targetArray[this.data.targetValue].name;
    }
    const requestData = {
      startMode: this.data.startMode,
      id: this.data.missionId,
      userId,
      userName,
      projectId,
      start,
      end,
      front,
      back,
      last,
      status,
      init,
      name
    }

    if (this.data.startMode === 0) {
      requestData.start = this.data.missionStart;
      requestData.end = this.data.missionEnd;
    } else if (this.data.startMode === 1) {
      if (this.data.missionRequest) {
        requestData.request = {
          name: this.data.missionRequest.description,
          userName: this.data.missionRequest.name,
          userId: this.data.missionRequest._id,
          consignor: getApp().globalData.userInfo._id,
          back: [],
          front: [],
          projectId
        }
      } else {
        requestData.front.push(this.data.missionStart._id)
      }
      requestData.last = this.data.missionLast;
    }
    wx.cloud.callFunction({
        name: 'makeMission',
        data: requestData
      })
      .then(() => {
        // console.log(res)
        wx.showToast({
          title: '创建成功',
        })
        wx.navigateBack({
          delta: 1,
        })
      }).catch(err => {
        console.log(err)
        wx.showToast({
          icon: 'none',
          title: '发生错误',
        })
        this.setData({
          confirmed: false
        })
      })
  },

})

const symbols = wx.getSystemInfoSync().platform === 'ios' ? '/' : '-';

function getLocalString(date) {
  return `${date.getFullYear()}${symbols}${date.getMonth() + 1}${symbols}${date.getDate()}`
}

function getDate(str) {
  if (typeof str == 'string') {
    const tempArr = str.split(/[-/\\_]/);
    return new Date(tempArr[0], tempArr[1] - 1, tempArr[2])
  } else {
    return new Date(str)
  }
}